#include "CF_Includes.h"

FILE *CCF_CFGReader::file = NULL;

bool CCF_CFGReader::Open (char *szFileName) {
	if (file != NULL) return false;
	if (file = fopen (szFileName, "rb")) return true;
	return false;
}

void CCF_CFGReader::Close () {
	if (file != NULL) fclose (file);
	file = NULL;
}

bool CCF_CFGReader::ReadNextEntry (char **ppNameOut, char **ppValueOut) {
	if (file == NULL) return false;
	if (feof (file)) return false;
	char c;
	// Adjust file pointer to point to next entry (if any)
	while (true) {
		fread (&c, 1, 1, file);
		if (feof (file)) return false;
		if ((c != ' ') && (c != '\t') && (c != '\n') && (c != '\r')) {
			if (c == '[') {	// Comment start, skip until enclosing square brace is found
				while (true) {
					fread (&c, 1, 1, file);
					if (feof (file)) {	// Error, unexpected end of file

						return false;
					}
					if (c == ']') break;
				}
			} else {	// It is not a comment, then is must be an entry
				fseek (file, -1, SEEK_CUR);
				break;
			}
		}
	}
	char buf [1000];
	int nChars;
	// Read entry name
	nChars = 0;
	while (true) {
		fread (&buf [nChars], 1, 1, file);
		if (buf[nChars] != '=') {	// Read until '=' is reached
			if ((buf[nChars] != ' ') && (buf[nChars] != '\t'))	// Skip spaces and tabs
				nChars++;
		}
		else {
			buf[nChars] = 0;
			break;
		}
	}
	if (nChars == 0) return false;
	*ppNameOut = new char [nChars + 1];
	for (int i = 0; i <= nChars; i++) (*ppNameOut) [i] = buf [i];
	// Skip until double quotation mark is reached
	c = 0;
	while (c != '\"') fread (&c, 1, 1, file);
	// Read entry value
	nChars = 0;
	while (true) {
		fread (&buf [nChars], 1, 1, file);
		if (buf[nChars] != '\"') {	// Read until double quotation mark is reached
			nChars++;
		}
		else {
			buf[nChars] = 0;
			break;
		}
	}
	if (nChars == 0) {
		delete *ppNameOut;
		return false;
	}
	*ppValueOut = new char [nChars + 1];
	for (int i = 0; i <= nChars; i++) (*ppValueOut) [i] = buf [i];

	return true;
}
